//
//  ChuwuViewController.m
//  HomeIn
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "ChuwuViewController.h"
#import "ChuwuModel.h"
#import "ChuwuCell.h"
#import "ChuwuDetailViewController.h"
@interface ChuwuViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *modelArray;//model数组

@property (nonatomic, assign) NSInteger currentPage;//记录当前page
@property (nonatomic, assign) BOOL isUpLoading;//标记是否为上拉

@end

@implementation ChuwuViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //视图将要出现的时候刷新
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.modelArray = [NSMutableArray array];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH - 20, HEIGHT / 4);
    //设置item的行间距
    flowLayout.minimumLineSpacing = 10;
    //设置item的上,左,下,右 边界距离
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //滑动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    //collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 113) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = RGBA(236, 235, 241, 1);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    //注册cell
    [self.collectionView registerClass:[ChuwuCell class] forCellWithReuseIdentifier:@"reuse"];
    
    self.currentPage = 0;//默认请求下来的数据为第0页
    self.isUpLoading = NO;//默认是下拉状态
    [self getAFNetWorkingData:self.currentPage];//请求cell数据
    [self addHeaderRefresh];
    [self addFooterRefresh];
    
}

//下拉刷新
- (void)addHeaderRefresh
{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = NO;//标记为下拉
        NSLog(@"下拉");
        self.currentPage = 0;//刷新首页,只要下拉,就请求第0页数据
        //重新请求数据
        [self getAFNetWorkingData:self.currentPage];
    }];
    
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}

//上拉刷新
- (void)addFooterRefresh
{
    
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = YES;//标记为上拉
        NSLog(@"上拉");
        self.currentPage += 20;//上拉一次,页码+20
        
        [self getAFNetWorkingData:self.currentPage];
    }];
    
}

//AFN请求数据
-(void)getAFNetWorkingData:(NSInteger)page
{
    NSString *urlString = [NSString stringWithFormat:@"http://api.bohejiaju.com/v1/channels/12/items?limit=20&offset=%ld", self.currentPage];
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //下拉时,删除之前的,存入最新的数据
        if (self.isUpLoading == NO)
        {
            //如果是下拉刷新,清空数组
            [self.modelArray removeAllObjects];
            
        }
        //上拉刷新,则往数组里增加,页面上也增加
        NSMutableDictionary *dictionary = responseObject;
        NSMutableArray *array = [[dictionary objectForKey:@"data"] objectForKey:@"items"];
        
        for (NSMutableDictionary *dic in array)
        {
            ChuwuModel *chuwuModel = [[ChuwuModel alloc] init];
            [chuwuModel setValuesForKeysWithDictionary:dic];
            
            [self.modelArray addObject:chuwuModel];
            
        }
        
        //结束下拉上拉刷新
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        
        
        [self.collectionView reloadData];
        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             
             NSLog(@"error = %@",error);
             
         }];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.modelArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从cell重用池里取
    ChuwuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    cell.layer.masksToBounds = YES;//masksToBounds裁剪掉边框
    cell.layer.cornerRadius = 5;//设置圆角度
    
    ChuwuModel *chuwuModel = [self.modelArray objectAtIndex:indexPath.row];
    cell.chuwuModel = chuwuModel;
    return cell;
    
}

//点击item触发方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ChuwuDetailViewController *chuwuDetailVC = [[ChuwuDetailViewController alloc] init];
    ChuwuModel *chuwuModel = [self.modelArray objectAtIndex:indexPath.row];
    chuwuDetailVC.chuwuModel = chuwuModel;//属性传值
    
    //push到详情的时候让tabBar(工具栏)消失
    chuwuDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chuwuDetailVC animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
